package com.huidu.bitrade.job;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.huidu.bitrade.entity.CoinThumb;
import com.huidu.bitrade.entity.ExchangeTrade;
import com.huidu.bitrade.entity.TradePlate;
import com.huidu.bitrade.handler.NettyHandler;
import com.huidu.bitrade.service.ExchangeCoinService;
import com.huidu.bitrade.util.NettyPushDataUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;

//@Component
@Slf4j
public class ExchangePushJobNew {
    @Autowired
    private ExchangeCoinService coinService;
    @Autowired
    private SimpMessagingTemplate messagingTemplate;
    @Autowired
    private NettyHandler nettyHandler;
    @Autowired
    private NettyPushDataUtil nettyPushDataUtil;
    private Map<String,List<ExchangeTrade>> tradesQueue = new HashMap<>();
    private Map<String,List<TradePlate>> plateQueue = new HashMap<>();
    private Map<String,List<CoinThumb>> thumbQueue = new HashMap<>();

    private Random rand = new Random();
    private HashMap<String, TradePlate> plateLastBuy = new HashMap<>(); // 最后一次推送的盘口，仅仅是为了虚拟推送二设立的
    private HashMap<String, TradePlate> plateLastSell = new HashMap<>(); // 最后一次推送的盘口，仅仅是为了虚拟推送二设立的
    private Map<String, CoinThumb> lastPushThumb = new HashMap<>(); // 最后一次推送的Thumb


    public void addTrades(String symbol, List<ExchangeTrade> trades){
//        List<ExchangeTrade> list = tradesQueue.get(symbol);
//        if(list == null){
//            list = new ArrayList<>();
//            tradesQueue.put(symbol,list);
//        }
//        synchronized (list) {
//            list.addAll(trades);
//        }
        log.info("addTrades 开始推送数据");
        messagingTemplate.convertAndSend("/topic/market/trade/" + symbol, trades);
//        nettyPushDataUtil.pushMarketTrade(symbol,trades);
    }

//    @Scheduled(fixedRate = 800)
//    public void pushTrade(){
//        Iterator<Map.Entry<String,List<ExchangeTrade>>> entryIterator = tradesQueue.entrySet().iterator();
//        while (entryIterator.hasNext()){
//            Map.Entry<String,List<ExchangeTrade>> entry =  entryIterator.next();
//            String symbol = entry.getKey();
//            List<ExchangeTrade> trades = entry.getValue();
//            if(trades.size() > 0){
//                synchronized (trades) {
//                    messagingTemplate.convertAndSend("/topic/market/trade/" + symbol, trades);
//                    trades.clear();
//                }
//            }
//        }
//    }

    public void addPlates(String symbol, TradePlate plate){
//        List<TradePlate> list = plateQueue.get(symbol);
//        if(list == null){
//            list = new ArrayList<>();
//            plateQueue.put(symbol,list);
//        }
//        synchronized (list) {
//            list.add(plate);
//        }
//
//        if(plate.getDirection() == ExchangeOrderDirection.BUY) {
//            // 更新最新盘口
//            synchronized (plateLastBuy) {
//                plateLastBuy.put(symbol, plate);
//            }
//        }
//        if(plate.getDirection() == ExchangeOrderDirection.SELL) {
//            // 更新最新盘口
//            synchronized (plateLastSell) {
//                plateLastSell.put(symbol, plate);
//            }
//        }
        //websocket推送盘口信息
        log.info("addPlates 开始");
        log.info(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_MS_PATTERN));
        messagingTemplate.convertAndSend("/topic/market/trade-plate/" + symbol, plate.toJSON(24));
        //websocket推送深度信息
        log.info(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_MS_PATTERN));
        messagingTemplate.convertAndSend("/topic/market/trade-depth/" + symbol, plate.toJSON(50));
        //netty推送
        log.info(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_MS_PATTERN));
        nettyHandler.handlePlate(symbol, plate);

        nettyPushDataUtil.pushMarketPlate(symbol,plate.toJSON(24));
        nettyPushDataUtil.pushMarketDepth(symbol,plate.toJSON(50));
    }

//    @Scheduled(fixedDelay = 1000)
//    public void pushPlate(){//TODO 这个任务的执行必须是当前盘口有人挂单，才会推送数据
//        Iterator<Map.Entry<String,List<TradePlate>>> entryIterator = plateQueue.entrySet().iterator();
//        while (entryIterator.hasNext()){
//            Map.Entry<String,List<TradePlate>> entry =  entryIterator.next();
//            String symbol = entry.getKey();
//            List<TradePlate> plates = entry.getValue();
//            if(plates.size() > 0){
//                boolean hasPushAskPlate = false;
//                boolean hasPushBidPlate = false;
//                synchronized (plates) {
//                    for(TradePlate plate:plates) {
//                        if(plate.getDirection() == ExchangeOrderDirection.BUY && !hasPushBidPlate) {
//                            hasPushBidPlate = true;
//                        }
//                        else if(plate.getDirection() == ExchangeOrderDirection.SELL && !hasPushAskPlate){
//                            hasPushAskPlate = true;
//                        } else {
//                            continue;
//                        }
//                        //websocket推送盘口信息
//                        messagingTemplate.convertAndSend("/topic/market/trade-plate/" + symbol, plate.toJSON(24));
//                        //websocket推送深度信息
//                        messagingTemplate.convertAndSend("/topic/market/trade-depth/" + symbol, plate.toJSON(50));
//                        //netty推送
//                        nettyHandler.handlePlate(symbol, plate);
//                    }
//
//                    plates.clear();
//                }
//            }else{
//                TradePlate plateBuy = plateLastBuy.get(symbol);
//                TradePlate plateSell = plateLastSell.get(symbol);
//                if(plateBuy != null) {
//                    // 随机修改盘口数据，然后推送
//                    List<TradePlateItem> list = plateBuy.getItems();
//                    if(list.size() > 9) { // 只要大于随机数的种子就行，这里的4是随意设置的
//                        //websocket推送盘口信息
//                        messagingTemplate.convertAndSend("/topic/market/trade-plate/" + symbol, plateBuy.toJSON(24));
//                        //websocket推送深度信息
//                        messagingTemplate.convertAndSend("/topic/market/trade-depth/" + symbol, plateBuy.toJSON(50));
//                        //netty推送
//                        nettyHandler.handlePlate(symbol, plateBuy);
////                        }
//                    }
//                }
//                if(plateSell != null) {
//                    // 随机修改盘口数据，然后推送
//                    List<TradePlateItem> list = plateSell.getItems();
//                    if(list.size() > 9) { // 只要大于随机数的种子就行，这里的4是随意设置的
//                        //websocket推送盘口信息
//                        messagingTemplate.convertAndSend("/topic/market/trade-plate/" + symbol, plateSell.toJSON(24));
//                        //websocket推送深度信息
//                        messagingTemplate.convertAndSend("/topic/market/trade-depth/" + symbol, plateSell.toJSON(50));
//                        //netty推送
//                        nettyHandler.handlePlate(symbol, plateSell);
////                        }
//                    }
//                }
//            }
//        }
//    }

    public void addThumb(String symbol, CoinThumb thumb){
        List<CoinThumb> list = thumbQueue.get(symbol);
        if(list == null){
            list = new ArrayList<>();
            thumbQueue.put(symbol,list);
        }
        synchronized (list) {
            list.add(thumb);
        }
    }


    @Scheduled(fixedRate = 1000)
    public void pushThumb(){
//        log.info("pushThumb 定时推送数据");
        Iterator<Map.Entry<String,List<CoinThumb>>> entryIterator = thumbQueue.entrySet().iterator();
        while (entryIterator.hasNext()){
            Map.Entry<String,List<CoinThumb>> entry =  entryIterator.next();
            String symbol = entry.getKey();
            List<CoinThumb> thumbs = entry.getValue();
            if(thumbs.size() > 0){
                synchronized (thumbs) {
                    CoinThumb pushThumb = thumbs.get(thumbs.size() - 1);
                    if(lastPushThumb.get(symbol) != null && lastPushThumb.get(symbol).getVolume().compareTo(pushThumb.getVolume()) > 0){
                        pushThumb.setVolume(lastPushThumb.get(symbol).getVolume());
                    }
                    pushThumb.setTime(System.currentTimeMillis());
                    messagingTemplate.convertAndSend("/topic/market/thumb",thumbs.get(thumbs.size() - 1));
                    nettyPushDataUtil.pushMarketSpot(symbol, thumbs.get(thumbs.size() - 1));
                    lastPushThumb.put(symbol, thumbs.get(thumbs.size() - 1));
                    thumbs.clear();
                }
            }
        }
    }
}
